﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using TSL_Tools.SqlTools;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Data.SqlClient;

namespace PerfmonImportExport
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        int selectedRunId = -1;
        string selectedMachine = "";
        bool bPopulatingMachinesList = false;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            tbSqlConn.Text = Properties.Settings.Default.ConnectionString;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Properties.Settings.Default.ConnectionString = tbSqlConn.Text;
        }

        private void btnGetRuns_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Input.Cursor _cursor = this.Cursor;
            this.Cursor = Cursors.Wait;

            try
            {
                dgResults.Items.Clear();
                dgMachines.Items.Clear();
                selectedRunId = -1;
                selectedMachine = "";
                TalkToSql tts = new TalkToSql(tbSqlConn.Text);
                DataTable _table = new DataTable();
                string sqlCmd = "SELECT LoadTestRunId AS 'Run #', LoadTestName, StartTime, RunDuration, [Description] FROM LoadTestRun WHERE Outcome != 'InProgress' ORDER BY LoadTestRunId DESC";
                tts.ExecuteReaderTable(sqlCmd, out _table);
                dgResults.ItemsSource = _table.AsDataView();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(String.Format("A SQL Error occurred. This is most likely due to the connection string you are using. Please check the connection string and then try again. \r\n\r\n{0}", ex.Message));
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("An unknown exception occurred. Please report this to the owner of the application.\r\n\r\n{0}", ex.Message));
            }
            finally
            {
                this.Cursor = _cursor;
            }
        }

        private void btnImportPerfmon_Click(object sender, RoutedEventArgs e)
        {
            if(selectedRunId == -1)
            {
                MessageBox.Show("Please select the run that you want the counters imported into.");
                return;
            }

            // Configure save file dialog box
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            //dlg.InitialDirectory = Properties.Settings.Default.FolderToStoreResults;
            dlg.DefaultExt = ".csv";
            dlg.Filter = "Perfmon CSV Files (.csv)|*.csv";

            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                tsslMessage.Content = "Importing Perfmon Counters";
                System.Windows.Input.Cursor _cursor = this.Cursor;
                this.Cursor = Cursors.Wait;
               
                try
                {
                    string sqlCmd = String.Format("SELECT DISTINCT MachineName FROM LoadTestPerformanceCounterCategory WHERE LoadTestRunId = {0}", selectedRunId);
                    TalkToSql tts = new TalkToSql(tbSqlConn.Text);
                    List<string> machines = new List<string>();
                    tts.ExecuteReaderStringList(sqlCmd, out machines);

                    PerfmonImportClass pis = new PerfmonImportClass(selectedRunId, tbSqlConn.Text, 60, 3000, machines);
                    string returnValue = pis.PerformTheImport(dlg.FileName);
                    tsslMessage.Content = returnValue;

                }
                catch (SqlException ex)
                {
                    MessageBox.Show(String.Format("A SQL Error occurred. This is most likely due to the connection string you are using. Please check the connection string and then try again. \r\n\r\n{0}", ex.Message));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format("An unknown exception occurred. Please report this to the owner of the application.\r\n\r\n{0}", ex.Message));
                }
                finally
                {
                    this.Cursor = _cursor;
                    // Add your cleanup code here
                    tsslMessage.Content = "Error occurred. Processing did not complete.";
                }
        
            }
        }

        private void btnExportPerfmon_Click(object sender, RoutedEventArgs e)
        {
            if (selectedRunId == -1)
            {
                MessageBox.Show("Please select the run that contains the counters you want to export.");
                return;
            }

            if (selectedMachine == "")
            {
                MessageBox.Show("Please select the machine that you want to export counters for.");
                return;
            }

            string sFileName = "Exception thrown";  //Set string to error text. It will get overwritten if the method succeeds.
            System.Windows.Input.Cursor _cursor = this.Cursor;
            this.Cursor = Cursors.Wait;

            TimeSpan tsTotal = TimeSpan.Zero;

            try
            {
                if (!Directory.Exists(tbFileFolder.Text))
                {
                    Directory.CreateDirectory(tbFileFolder.Text);
                }

                PerfmonExportClass pes = new PerfmonExportClass(tbSqlConn.Text, 60, 3000);
                tsslMessage.Content = "Starting the SQL portion of the export";
                tsslMessage.UpdateLayout();

                TimeSpan ts = pes.ExportPerfmonCountersPart1(selectedMachine, selectedRunId, tbFileFolder.Text, tbSqlConn.Text);
                tsslMessage.Content = String.Format("Completed the SQL Query part of the export in {0} seconds.. Building CSV Export Table", ts.TotalSeconds);

                tsslMessage.UpdateLayout();
                DateTime dt = DateTime.Now;
                sFileName = pes.ExportPerfmonCountersPart2(selectedMachine, selectedRunId, tbFileFolder.Text, tbSqlConn.Text);
                tsTotal = (TimeSpan)(DateTime.Now - dt);
                tsTotal += ts;
            }
            catch (SqlException ex)
            {
                MessageBox.Show(String.Format("A SQL Error occurred. This is most likely due to the connection string you are using. Please check the connection string and then try again. \r\n\r\n{0}", ex.Message));
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("An unknown exception occurred. Please report this to the owner of the application.\r\n\r\n{0}", ex.Message));
            }
            finally
            {
                this.Cursor = _cursor;
                tsslMessage.Content = String.Format("File Created: {0}  -  Total Time {1} seconds", sFileName, tsTotal);
            }
        }

        private void dgResults_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bPopulatingMachinesList = true;
            System.Windows.Input.Cursor _cursor = this.Cursor;
            this.Cursor = Cursors.Wait;

            try
            {
                selectedRunId = -1;
                foreach (object obj in dgResults.SelectedItems)
                {
                    DataRowView row = (DataRowView)obj;
                    int _runId;
                    Int32.TryParse(row[0].ToString(), out _runId);
                    selectedRunId = _runId;
                }
                tsslMessage.Content = "Selected Run: " + selectedRunId.ToString();

                selectedMachine = "";
                TalkToSql tts = new TalkToSql(tbSqlConn.Text);
                DataTable _table = new DataTable();
                string sqlCmd = String.Format("SELECT DISTINCT MachineName FROM LoadTestPerformanceCounterCategory WHERE LoadTestRunId = {0}", selectedRunId);
                tts.ExecuteReaderTable(sqlCmd, out _table);
                dgMachines.ItemsSource = _table.AsDataView();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(String.Format("A SQL Error occurred. This is most likely due to the connection string you are using. Please check the connection string and then try again. \r\n\r\n{0}", ex.Message));
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("An unknown exception occurred. Please report this to the owner of the application.\r\n\r\n{0}", ex.Message));
            }
            finally
            {
                this.Cursor = _cursor;
                bPopulatingMachinesList = false;
            }
        }

        private void dgMachines_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedMachine = "";
            if (!bPopulatingMachinesList)
            {
                foreach (object obj in dgMachines.SelectedItems)
                {
                    DataRowView row = (DataRowView)obj;
                    selectedMachine = row[0].ToString();
                }
                tsslMessage.Content = "Selected Machine: " + selectedMachine;
            }
        }

        private void btnMenuHelpTopic0_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("Help File.rtf");           
        }
    }
}

